package com.jcfk.system.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.core.utils.BeanUtils;
import com.jcfk.common.core.utils.IdUtils;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.system.dao.DataboardCatalogDao;
import com.jcfk.system.domain.dto.DataboardCatalogDTO;
import com.jcfk.system.domain.po.RefUserOrganizationMapping;
import com.jcfk.system.domain.po.DataboardCatalog;
import com.jcfk.system.domain.query.DataboardCatalogQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 数据看板目录 业务逻辑
 *
 * @author qinjiaxing
 */
@Service
public class DataboardCatalogService extends BaseService<DataboardCatalogDao, DataboardCatalog> {

    /**
     * 根据条件获取数据看板目录列表
     *
     * @param query 查询条件
     * @return List<CustomMultilevelKindDTO>
     */
    public List<DataboardCatalogDTO> getList(DataboardCatalogQuery query) {
        // 查询条件
        QueryWrapper<DataboardCatalog> qw = new QueryWrapper<>();

        if (!StrUtil.isEmpty(query.getCatalogName())) {
            qw.lambda().like(DataboardCatalog::getCatalogName, query.getCatalogName());
        }

        qw.lambda().eq(DataboardCatalog::getDeleted, 0);
        qw.lambda().orderByAsc(DataboardCatalog::getSort);

        // 查询数据
        List<DataboardCatalog> databoardCatalogList = super.list(qw);
        List<DataboardCatalogDTO> databoardCatalogArray = new ArrayList<>();
        for (DataboardCatalog DataboardCatalog : databoardCatalogList) {
            DataboardCatalogDTO DataboardCatalogDTO = new DataboardCatalogDTO();
            BeanUtils.copyProperties(DataboardCatalog, DataboardCatalogDTO);
            databoardCatalogArray.add(DataboardCatalogDTO);
        }
        return databoardCatalogArray;
    }

    /**
     * 获取指定目录列表的上级目录
     *
     * @param dtos
     * @return
     */
    public List<DataboardCatalogDTO> getSuperCatalogs(List<DataboardCatalogDTO> dtos) {

        List<DataboardCatalogDTO> superOrganizations = new ArrayList<>();
        if (dtos.size() <= 0) return superOrganizations;

        List<String> ids = new ArrayList<>();
        for (DataboardCatalogDTO dto : dtos) {
            String[] superIds = dto.getAllId().split(",");
            List<String> idList = new ArrayList<>(Arrays.asList(superIds));
            if (idList.size() > 1) {
                idList.remove(1);
            }
            ids.addAll(idList);
        }

        // 校验编码
        QueryWrapper<DataboardCatalog> qw = new QueryWrapper<>();
        qw.lambda().in(DataboardCatalog::getId, ids);
        qw.lambda().orderByAsc(DataboardCatalog::getSort);
        List<DataboardCatalog> DataboardCatalogList = this.baseMapper.selectList(qw);
        superOrganizations = DataboardCatalogList.stream().map(p -> {
            DataboardCatalogDTO DataboardCatalogDTO = new DataboardCatalogDTO();
            BeanUtils.copyProperties(p, DataboardCatalogDTO);
            return DataboardCatalogDTO;
        }).collect(Collectors.toList());

        return superOrganizations;
    }

    /**
     * 根据 主键 获取单条数据
     *
     * @param id 主键
     * @return DataboardCatalogDTO
     */
    public DataboardCatalogDTO get(String id) {
        // 查询数据
        DataboardCatalog item = this.baseMapper.selectById(id);
        DataboardCatalogDTO DataboardCatalogDTO = new DataboardCatalogDTO();
        BeanUtils.copyProperties(item, DataboardCatalogDTO);
        return DataboardCatalogDTO;
    }

    /**
     * 校验合法性
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(DataboardCatalogDTO dto) {
        Integer count = 0;

        return RetResult.ok();
    }

    /**
     * 插入对象
     *
     * @param dto 插入对象
     * @return DataboardCatalog
     */
    @Transactional(rollbackFor = Exception.class)
    public DataboardCatalogDTO insert(DataboardCatalogDTO dto) {

        DataboardCatalog item = new DataboardCatalog();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        item.setVersion(1L);
        this.setDefaultValue(item);
        item.setId(IdUtils.simpleUUID());
        item.setParentId(!StringUtils.isEmpty(dto.getParentId()) ? dto.getParentId() : "0");
        // 设置设置全主键、全编码、全名称
        this.setAllInfo(item);

        // 保存
        super.save(item);

        BeanUtils.copyProperties(item, dto);

        return dto;
    }

    /**
     * 更新对象
     *
     * @param dto 更新对象
     * @return CustomMultilevelKind
     */
    @Transactional(rollbackFor = Exception.class)
    public DataboardCatalogDTO update(DataboardCatalogDTO dto) {
        DataboardCatalog item = new DataboardCatalog();
        BeanUtils.copyProperties(dto, item);
        item.setParentId(!StringUtils.isEmpty(dto.getParentId()) ? dto.getParentId() : "0");
        // 默认数据
        this.setDefaultValue(item);
        // 设置设置全主键、全编码、全名称
        this.setAllInfo(item);
        // 保存
        super.updateById(item);

        return dto;
    }

    /**
     * 根据条件获取目录信息树
     *
     * @param query 查询条件
     * @return List<CustomMultilevelKindDTO>
     */
    public List<DataboardCatalogDTO> getTree(DataboardCatalogQuery query) {
        List<DataboardCatalogDTO> tree = new ArrayList<>();
        // 获取所有目录
        List<DataboardCatalogDTO> allList = this.getList(query);
        // 获取上级目录
        List<DataboardCatalogDTO> superList = this.getSuperCatalogs(allList);
        for (DataboardCatalogDTO dto : superList) {
            Optional<DataboardCatalogDTO> result = allList.stream().filter(p -> p.getId().equals(dto.getId())).findFirst();
            if (result.isPresent() == false) {
                allList.add(dto);
            }
        }

        Map<String, List<DataboardCatalogDTO>> parentChildMap = new HashMap<>();
        // 将节点按照父节点进行分组
        for (DataboardCatalogDTO node : allList) {
            String parentId = node.getParentId();
            parentChildMap.computeIfAbsent(parentId, k -> new ArrayList<>()).add(node);
        }

        // 递归组装树结构
        buildTree(tree, parentChildMap, "0");

        return tree;
    }

    private void addChildNodes(List<DataboardCatalogDTO> allList, DataboardCatalogDTO node) {
        List<DataboardCatalogDTO> childNodes = allList.stream().filter(p -> node.getId().equals(p.getParentId())).collect(Collectors.toList());
        node.setNodes(new ArrayList<>());
        for (DataboardCatalogDTO childNode : childNodes) {
            node.getNodes().add(childNode);
            // 创建子节点
            this.addChildNodes(allList, childNode);
        }
    }

    /**
     * 根据条件获取目录分页列表
     *
     * @param tree           树
     * @param parentChildMap 节点集合
     * @param parentId       父id
     */
    private static void buildTree(List<DataboardCatalogDTO> tree, Map<String, List<DataboardCatalogDTO>> parentChildMap, String parentId) {
        List<DataboardCatalogDTO> children = parentChildMap.get(parentId);
        if (children != null) {
            for (DataboardCatalogDTO child : children) {
                List<DataboardCatalogDTO> grandchildren = parentChildMap.get(child.getId());
                if (grandchildren != null) {
                    buildTree(child.getNodes(), parentChildMap, child.getId());
                }
                tree.add(child);
            }
        }
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(DataboardCatalog item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

    }

    /**
     * 设置全主键、全编码、全名称
     */
    public void setAllInfo(DataboardCatalog item) {
        QueryWrapper<DataboardCatalog> qw = new QueryWrapper<>();
        qw.lambda().eq(DataboardCatalog::getId, item.getParentId());

        DataboardCatalog superCustomMultilevelKind = this.baseMapper.selectOne(qw);
        if (superCustomMultilevelKind == null) {
            item.setAllId(item.getId());
            item.setAllName(item.getCatalogName());
        } else {
            item.setAllId(superCustomMultilevelKind.getAllId() + "," + item.getId());
            item.setAllName(superCustomMultilevelKind.getAllName() + "," + item.getCatalogName());
        }
    }

    /**
     * 判断是否有下级目录
     *
     * @param id
     * @return
     */
    public Boolean isHaveChild(String id) {
        QueryWrapper<DataboardCatalog> qw = new QueryWrapper<>();
        qw.lambda().eq(DataboardCatalog::getParentId, id).eq(DataboardCatalog::getDeleted, 0);
        Integer count = this.baseMapper.selectCount(qw);
        return count > 0 ? true : false;
    }

    /**
     * 根据主键删除(逻辑删除)
     *
     * @param ids
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public void logicDeleteList(List<String> ids) {
        // 删除
        UpdateWrapper<DataboardCatalog> uw = new UpdateWrapper<>();
        uw.lambda().in(DataboardCatalog::getId, ids);
        uw.set("deleted", 1);
        this.update(uw);

    }

    /**
     * 根据主键删除(物理删除)
     *
     * @param ids
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteByIds(String[] ids) {
        Boolean result = true;
        super.removeByIds(Arrays.asList(ids));
        return result;
    }
}
